package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink01_Timer_Exec {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        KeyedStream<WaterSensor, Tuple> keyedStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .keyBy("id");

        //监控水位传感器的水位值，如果水位值在五秒钟之内连续上升，则报警，并将报警信息输出到侧输出流。
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //定义保存上一次水位的值
            private Integer lastVc = Integer.MIN_VALUE;

            //定义保存定时器的值
            private Long timer = Long.MIN_VALUE;

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.判断水位是否上升
                if (value.getVc() > lastVc) {
                    //水位上升
                    //2.查看是否注册定时器
                    if (timer == Long.MIN_VALUE) {
                        //没有注册定时器
                        //获取当前的处理时间
                        System.out.println("注册定时器"+ctx.getCurrentKey());
                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }
                } else {
                    //水位没有上升
                    //判断是否有定时器
                    if (timer != Long.MIN_VALUE) {
                        //删除定时器
                        System.out.println("删除定时器"+ctx.getCurrentKey());
                        ctx.timerService().deleteProcessingTimeTimer(timer);
                        //将保存定时器的值回复成默认值，以便后续来的数据注册定时器
                        timer = Long.MIN_VALUE;

                        //将上一次水位恢复成默认值
                        lastVc = Integer.MIN_VALUE;
                    }
                }
                //将当前水位保存到状态中，以便下一次水位做对比
                lastVc = value.getVc();

                out.collect(value.toString());
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //定时器触发，证明水位5秒连续上升
                ctx.output(new OutputTag<String>("警报") {
                }, "警报！！！！水位5s连续上升");
                //回复定时器的值
                timer = Long.MIN_VALUE;
            }
        });

        result.print();

        result.getSideOutput(new OutputTag<String>("警报") {
        }).print("侧流");

        env.execute();
    }
}
